<!--
 * @Author: 谢陈洁
 * @Date: 2025-06-30 08:25:44
 * @LastEditors: 谢陈洁
 * @LastEditTime: 2025-07-23 15:12:50
 * @Description: file content
-->
<template>
  <el-upload
    ref="uploadRef"
    list-type="picture-card"
    :file-list="fileList"
    :auto-upload="$attrs.action ? true : false"
    :show-file-list="true"
    :on-success="handleUploadSuccess"
    :on-remove="handleUploadRemove"
    :on-change="handleUploadChange"
    :on-preview="handlePreview"
    :on-exceed="handleUploadExceed"
  >
    <template #trigger>
      <slot :name="$attrs.slot">
        <el-icon><Plus /></el-icon>
      </slot>
    </template>
    <template #tip>
      <div class="el-upload__tip">{{ $attrs.tips }}</div>
    </template>
    <el-image-viewer
      v-if="previewVisible"
      :url-list="urlList"
      :z-index="9999"
      :initial-index="currentIndex"
      @close="handlePreviewClose"
    />
  </el-upload>
</template>

<script setup lang="ts">
  import { genFileId, type UploadFile, type UploadProps, type UploadRawFile } from 'element-plus'
  const attrs = useAttrs()
  console.log('CustomUpload attrs:', attrs)
  const props = defineProps({
    modelValue: { type: [Array as () => UploadFile[], String], default: () => [] }
  })
  console.log('CustomUpload props:', props)
  const emit = defineEmits(['update:modelValue'])

  const urlList = ref<string[]>([])
  const fileList = ref<UploadFile[]>([])
  const previewVisible = ref(false)
  const currentIndex = ref(0)

  // 监听外部 v-model 变化同步 fileList
  watch(
    () => props.modelValue,
    (val: any) => {
      if (!val) return []
      if (val instanceof Array) {
        fileList.value = val
      } else {
        fileList.value = [
          {
            url: val,
            uid: genFileId()
          }
        ]
      }
    },
    { immediate: true }
  )

  function handleUploadSuccess(response: any, file: UploadFile, fileList: UploadFile[]) {
    console.log('Upload success:', response, file, fileList)
    emit('update:modelValue', fileList)
    if (attrs.onSuccess) attrs.onSuccess(response, file, fileList)
  }
  function handleUploadRemove(file: UploadFile, fileList: UploadFile[]) {
    emit('update:modelValue', fileList)
    if (attrs.onRemove) attrs.onRemove(file, fileList)
  }
  function handleUploadChange(file: UploadFile, fileList: UploadFile[]) {
    console.log('File changed:', file, fileList)
    emit('update:modelValue', fileList)
    if (attrs.onChange) attrs.onChange(file, fileList)
  }
  function handlePreview(file: UploadFile) {
    urlList.value = (props.modelValue || [])
      .map((f: any, index: number) => {
        const url = f.url || f.response?.url || f.thumbUrl
        if (file.url === url) {
          currentIndex.value = index
        }
        return url
      })
      .filter(Boolean)
    currentIndex.value = (props.modelValue || []).findIndex((f: UploadFile) => f.uid === file.uid)
    previewVisible.value = true
  }
  function handlePreviewClose() {
    previewVisible.value = false
  }
  const handleUploadExceed: UploadProps['onExceed'] = (files: UploadRawFile[]) => {
    ElMessage.warning(
      `当前限制选择 ${attrs.limit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + (props.modelValue || []).length} 个文件`
    )
  }
</script>
